package com.bocai.grainshop.cart.interceptor;

import com.bocai.common.constant.AuthServerConstant;
import com.bocai.common.constant.CartConstant;
import com.bocai.common.vo.MemberVo;
import com.bocai.grainshop.cart.to.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

//拦截器需要配置Config才能生效
public class UserInterceptor implements HandlerInterceptor {

    //确保controller  interceptor service dao  是同一线程
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * @Author: SunJinbo
     * @Description  获取请求之前，判断是否为临时用户 封装一些数据
     * @Param [request, response, handler]
     * @return boolean
     * @Data Created in 2022/4/17 15:30
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberVo memberVo = (MemberVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(memberVo!=null){
            //用户登录
            userInfoTo.setUserId(memberVo.getId());
        }
        //获取cooike中带来的user_key
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equalsIgnoreCase(CartConstant.TEMP_USER_COOKIE_NAME)){
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                    break;
                }
            }
        }
        //如果用户第一次 登录 但没有临时用户的user_key
        if(!StringUtils.hasText(userInfoTo.getUserKey())){
            String s = UUID.randomUUID().toString();
            userInfoTo.setUserKey(s);
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * @Author: SunJinbo
     * @Description  处理业务之后
     * @Param [request, response, handler, modelAndView]
     * @return void
     * @Data Created in 2022/4/17 15:31
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //拿到同一线程的userInfo
        UserInfoTo userInfoTo = threadLocal.get();
        if(userInfoTo.getTempUser() == false){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey());
            cookie.setDomain("grainshop.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
